<template>
  <branch-base
    :loading-value="loadingValue"
    :title="cfg.title"
    :data="cfg.data"
    :close="cfg.close === 'true'"
    :close-text="cfg.close_text"
    :skip="cfg.skip !== 'false'"
    :type="cfg.type"
    from="ssml"
    @click="handClick"
    @close="closeBranch"
  />
</template>

<script lang="ts" setup name="BranchNodeCard">
import { useUIStore } from "@/store/ui";
import { useTrack } from '@/hooks'

const props = defineProps({
  cfg: {
    type: Object,
    default: () => ({}),
  },
});
const UI = useUIStore();

let loadingTimer = null;
let delayTimer = null

const loadingTime = computed(() => props.cfg['loading_time'])
const delayTime = computed(() => props.cfg['delay_time'])
const loadingValue = ref(0)

const handClick = (node) => {
  const { setTrack } = useTrack();
  if (props.cfg.type === 'ask') {
    // 问答互动上报统计
    setTrack({ name: 'interactive', type: 'ask' });
  } else {
    // 卡片引导点击统计
    setTrack({ name: 'interactive', type: 'click' });
  };
  if (node?.skip) {
    UI.go({ ...props.cfg.event_click, axis_id: props.cfg.axis_id });
  } else {
    UI.go({ ...node.event_click, axis_id: props.cfg.axis_id });
  }
}

const closeBranch = () => {
  UI.delUI(props.cfg.axis_id)
}

const loadingLoop = () => {
  loadingValue.value = loadingTime.value;
  loadingTimer = setInterval(() => {
    loadingValue.value -= 1;
    if (loadingValue.value <= 0) {
      closeBranch();
    }
  }, 1000);
};

const init = () => {
  if (loadingTime.value) {
    loadingLoop();
  };
};

const destroy = () => {
  if (loadingTimer) {
    clearInterval(loadingTimer);
    loadingTimer = null;
    loadingValue.value = 0;
  }
  if (delayTimer) {
    clearTimeout(delayTimer);
    delayTimer = null;
  }
}

onMounted(() => {
  if (props.cfg.close === 'true') {
    if (delayTime.value) {
      delayTimer = setTimeout(init, delayTime.value * 1000);
    } else {
      init();
    }
  }
})

onBeforeUnmount(() => {
  destroy()
})
</script>

